package job

import (
	"context"
	"encoding/json"
	"gcrontab/common"
	"github.com/coreos/etcd/clientv3"
)

//向etcd添加
func (j *JobMgr) SaveJob(job *common.Job) (oldJob *common.Job, err error) {
	jobVal, err := json.Marshal(job)
	if err != nil {
		return
	}
	//保存
	putResp, err := j.kv.Put(context.TODO(), common.JOB_SAVE_DIR+job.Name, string(jobVal), clientv3.WithPrevKV())
	if err != nil {
		return
	}
	//更新则返回旧值
	if putResp.PrevKv != nil {
		oldJobObj := common.Job{}
		err = json.Unmarshal(putResp.PrevKv.Value, &oldJobObj)
		if err != nil {
			return
		}
		oldJob = &oldJobObj
	}
	return oldJob, nil
}

//删除
func (j *JobMgr) DeleteJob(name string) (oldJob []*common.Job, err error) {
	delResp, err := j.kv.Delete(context.TODO(), common.JOB_SAVE_DIR+name, clientv3.WithPrevKV())
	if err != nil {
		return
	}
	//返回删除的信息
	if len(delResp.PrevKvs) > 0 {
		oldJobObj := common.Job{}
		for _, val := range delResp.PrevKvs {
			if err = json.Unmarshal(val.Value, &oldJobObj); err != nil {
				return
			}
			oldJob = append(oldJob, &oldJobObj)
		}
	}
	return oldJob, nil
}

//获取job列表
func (j *JobMgr) GetJobList() (jobs []*common.Job, err error) {
	getResp, err := j.kv.Get(context.TODO(), common.JOB_SAVE_DIR, clientv3.WithPrefix())
	if err != nil {
		return
	}
	jobs = make([]*common.Job, 0)
	if len(getResp.Kvs) > 0 {
		for _, val := range getResp.Kvs {
			oldJobObj := &common.Job{}
			if err = json.Unmarshal(val.Value, oldJobObj); err != nil {
				continue
			}
			jobs = append(jobs, oldJobObj)
		}
	}
	return jobs, nil
}

//关闭job
func (j *JobMgr) KillJob(name string) (err error) {
	//创建一个租约
	leaseResp, err := j.lease.Grant(context.TODO(), 1)
	if err != nil {
		return
	}
	leaseId := leaseResp.ID

	//设置killer标志
	if _, err = j.kv.Put(context.TODO(), common.JOB_KILLER_DIR+name, "", clientv3.WithLease(leaseId)); err != nil {
		return
	}
	return nil
}

//获取注册服务列表
func (j *JobMgr) GetRegisterList() (list []string, err error) {
	getResp, err := j.kv.Get(context.TODO(), common.REGISTER_DIR, clientv3.WithPrefix())
	if err != nil {
		return
	}
	list = make([]string, 0)
	if len(getResp.Kvs) > 0 {
		for _, val := range getResp.Kvs {
			//ps /cron/register/192.168.1.1
			ip := common.ExtractJobName(string(val.Key), common.REGISTER_DIR)
			list = append(list, ip)
		}
	}
	return list, nil
}
